<template>
  <section class="real-app">
    <input
      type="text"
      class="add-input"
      autofocus="autofocus"
      placeholder="接下来要做什么？"
      @keyup.enter="addTodo"
    >
    <item
      :todo="todo"
      v-for="todo in filteredTods"
      :key="todo.id"
      @del="deleteTodo"
      @change="changeTodo"
    />
    <tabs
      :filter="filter"
      :todos="todos"
      @toggle="toggleFilter"
      @clear="clearAllCompleted"
    />
  </section>
</template>

<script>
import Item from './item.vue'
import Tabs from './tabs.vue'
import axios from 'axios'
let id = 0
export default {
  data () {
    return {
      todos: [],
      filter: 'all'
    }
  },
  components: {
    Item,
    Tabs
  },
  computed: {
    filteredTods () {
      if (this.filter == "all") {
        return this.todos
      }
      const completed = this.filter === 'completed'
      return this.todos.filter(todo => todo.completed === completed)
    }
  },
  methods: {
    // 获取todo列表项
    getTododList () {
      axios.get('/api/lists').then(res => {
        console.log(res);
        if (res.data.status == "0") {
          this.todos = res.data.result.data;
        }
      }).catch(err => {}) 
    },
    // 添加项
    addTodo (e) {      
      axios.post('/api/lists/add', {
        content: e.target.value.trim(),
        completed: false
      }).then(res => {
        if (res.data.status == "0") {
          this.getTododList();
        }
      }).catch(err => {})
      e.target.value = '';
    },
    // 删除项
    deleteTodo(id) {
      axios.post('/api/lists/del', {id}).then(res => {
        if (res.data.status == "0") {
          this.getTododList();
        }
      }).catch(err => {})
    },
    // 改变项
    changeTodo(val) {
      axios.post('/api/lists/edit', {
        id: val.id,
        completed: val.completed
      }).then(res => {
        if (res.data.status == "0") {
          
        } else {
          this.getTododList();
        }
      }).catch(err => {})
    },
    toggleFilter(status) {
      this.filter = status
    },
    // 删除已完成
    clearAllCompleted() {
      axios.post('/api/lists/delCompleted').then(res => {
        if (res.data.status == "0") {
          this.getTododList();
        }
      }).catch(err => {})
    }
  },
  mounted () {
    this.getTododList()
  }
}
</script>

<style lang="stylus" scoped>
.real-app
  width 600px
  margin  0 auto
  box-shadow 0 0 5px #666
  .add-input 
    position relative
    margin 0
    width 100%
    font-size 24px
    font-family inherit
    font-weight inherit
    line-height 1.4em
    border none
    outline none
    color inherit
    box-sizing border-box
    font-smoothing antialiased
    padding 10px 16px 10px 36px
    border none
    box-shadow inset 0 -2px 1px rgba(0, 0, 0, 0.03)
</style>